<template>
  <view class="page-container" :style="{ height: pageHeight + 'px' }">
    <!-- 筛选栏 -->
<!--    <view class="filter-container">
      <view class="filter-item">
        <text>选择起始时间</text>
        <picker mode="date" :value="startDate" @change="handleStartDateChange">
          <view class="picker">
            <text>{{ startDate || '请选择起始日期' }}</text>
          </view>
        </picker>
      </view>
      <view class="filter-item">
        <text>选择结束时间</text>
        <picker mode="date" :value="endDate" @change="handleEndDateChange">
          <view class="picker">
            <text>{{ endDate || '请选择结束日期' }}</text>
          </view>
        </picker>
      </view>
    </view> -->

    <!-- 页面内容 -->
    <view class="bottom-button" @click="handleAddClick">
      <text class="plus-sign" :class="{ rotate: isRotating }">+</text>
    </view>

    <!-- 动态生成的可点击模块 -->
    <view class="modules-container">
      <view
        v-for="(group, groupIndex) in modules"
        :key="groupIndex"
        class="group-container"
      >
        <!-- 日期分隔线 -->
        <view v-if="group.date" class="date-divider">
          <text class="date-text">{{ group.date }}</text>
        </view>

        <!-- 每个拼车单的卡片 -->
        <view
          v-for="(item, index) in group.items"
          :key="index"
          class="clickable-module"
          @click="handleClick(item)"
        >
          <pinCell
            :pinID="item.pinID"
            :startTime="formatTime(item.departureTime)"
            :endTime="formatTime(item.arrivalTime)"
            :startPoint="item.startPoint"
            :endPoint="item.endPoint"
            :joinedPassengers="item.joinedPassengers"
            :totalPassengers="item.totalPassengers"
            :userName="item.leaderName"
            publishTime=" "
          />
        </view>
      </view>
    </view>

    <!-- 上拉加载更多提示 -->
    <view v-if="isLoading" class="loading-more">加载中...</view>
  </view>
</template>



<script>
import pinCell from '../../components/pinCell.vue';
import { PinlistAPI,getUserInfo,OrderAPI } from '../../services/api';
import { fetchPinInfo } from '../../services/pin';

export default {
  components: {
    pinCell
  },
  data() {
    return {
      modules: [],
	  istourist: true,
      pageHeight: 0,
      isLoading: false,
      currentPage: 1,
      pageSize: 10,
      isRotating: false,
      userName: '',
      userID: null,
      startDate: '', // 起始日期
      endDate: '', // 结束日期
	  iv:false,
    };
  },
  computed: {
    // 对模块的时间字段进行格式化
    modulesWithFormattedTime() {
      return this.modules.map(group => {
        return {
          ...group,
          items: group.items.map(module => ({
            ...module,
            formattedStartTime: this.formatTime(module.departureTime),
            formattedEndTime: this.formatTime(module.arrivalTime),
          }))
        };
      });
    }
  },
  methods: {
    handleAddClick() {
	  if (!this.iv){
		this.istourist=false;
	  }
		
	  if (!this.istourist){
	  		  if (this.isRotating) return;
	  		  this.isRotating = true;
	  		  uni.vibrateShort();
	  		  setTimeout(() => {
	  		    this.isRotating = false;
	  		    this.addModule();
	  		  }, 500);
	  }
	  else {
	  		  uni.showToast({
	  		    title: "请登陆后添加",
	  		    icon: "error",
	  		  });
	  }
    },
    addModule() {
      uni.navigateTo({
        url: "/pages/pinBranch/pinNew",
      });
    },
    handleClick(item) {
      console.log(`点击了活动单 ${item.pinID}`);
	  if (!this.iv){
		this.istourist=false;
	  }
	  if (!this.istourist){
		  uni.navigateTo({
		    url: `/pages/pinBranch/pinInvolve?pinID=${item.pinID}`,
		  });
	  }
      else {
		  uni.showToast({
		    title: "请登陆后查看",
		    icon: "error",
		  });
	  }
    },
    async loadPinData(reload = false) {
      if (this.isLoading) return;

      this.isLoading = true;

      try {
        if (reload) {
          this.modules = [];
          this.currentPage = 1;
        }

        const pinData = await PinlistAPI.getPinlists({
          page: this.currentPage,
          size: this.pageSize,
        });

        if (pinData && pinData.length) {
          const currentTime = new Date();

          // 筛选出发时间大于当前时间，并根据选择的起止时间过滤
          const filteredData = pinData.filter(item => {
            const departureTime = new Date(item.departureTime);
            const currentTime = new Date(); // 获取当前时间
            const oneDayLater = new Date(currentTime);
            oneDayLater.setHours(currentTime.getHours() - 24); // 当前时间加一天
          
            // 判断 departureTime 是否在当前时间和当前时间加一天之间
            return departureTime >= oneDayLater;
          });


          filteredData.sort((a, b) => {
            const timeA = new Date(a.departureTime);
            const timeB = new Date(b.departureTime);
            return timeA - timeB;
          });

          const enrichedData = await Promise.all(
            filteredData.map(async item => {
              const leaderName = await this.leaderConvert(item.pinID);
              return {
                ...item,
                leaderName,
              };
            })
          );

          // 按日期分组
          const groupedData = [];
          let currentGroup = [];
          let currentDate = "";

          enrichedData.forEach(item => {
            const departureDate = this.formatDate(item.departureTime);

            if (departureDate !== currentDate) {
              if (currentGroup.length > 0) {
                groupedData.push({ date: currentDate, items: currentGroup });
              }
              currentGroup = [];
              currentDate = departureDate;
            }

            currentGroup.push(item);
          });

          if (currentGroup.length > 0) {
            groupedData.push({ date: currentDate, items: currentGroup });
          }

          this.modules = groupedData;
          this.currentPage += 1;
        }
      } catch (error) {
        console.error("这里空空如也：", error);
        uni.showToast({
          title: "这里空空如也",
          icon: "none",
        });
      } finally {
        this.isLoading = false;
        uni.stopPullDownRefresh();
      }
    },
    async leaderConvert(pinID) {
      try {
        const pinInfo = await fetchPinInfo(pinID);
        return pinInfo.leaderName;
      } catch (error) {
        console.error(`Failed to fetch leader for pinID ${pinID}:`, error);
        return "未知";
      }
    },
	async fetchUsername() {
	  try {
	    const userinfo = await getUserInfo();
	    this.istourist = false;
	  } catch (error) {
	    console.error('获取用户名失败:', error);
	    this.istourist = true;
	  }
	},
    formatTime(timeString) {
      const date = new Date(timeString);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${year}/${month}/${day} ${hours}:${minutes}`;
    },
    formatDate(timeString) {
      const date = new Date(timeString);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}/${month}/${day}`;
    },
    onPullDownRefresh() {
      this.loadPinData(true);
    },
    handleStartDateChange(e) {
      this.startDate = e.detail.value;
      this.loadPinData(true); // 更新数据
    },
    handleEndDateChange(e) {
      this.endDate = e.detail.value;
      this.loadPinData(true); // 更新数据
    },
  },
  async onLoad() {
	this.iv= await OrderAPI.fetchOrderData();
	await this.fetchUsername();
    await this.loadPinData();
    uni.$on('updateModule', this.loadPinData);
  },
  onUnload() {
    uni.$off('updateModule', this.loadPinData);
  }
};
</script>




<style>
/* 设置 body 和 html 的背景颜色 */
html,
body {
  background-color: #FFF !important;
  height: 100%;
  margin: 0;
  padding: 0;
}

.page-container {
  position: relative;
  width: 100%;
  background-color: transparent;  /* 设置为透明背景 */
  padding-top: 0px;
  display: flex;  /* 设置为 flex 布局 */
  flex-direction: column;  /* 垂直排列 */
  align-items: center;  /* 水平居中对齐 */
}

.bottom-button {
  position: fixed;
  bottom: 0px;
  left: 0px;
  width: 100%;
  height: 60px;  /* 高度设置为 60px */
  background-color: #000;
  border-top-left-radius: 32px;
  border-top-right-radius: 32px;
  display: flex;
  align-items: center;  /* 垂直居中 */
  justify-content: center;  /* 水平居中 */
  z-index: 99;
  
}

.plus-sign {
  color: #fff;
  font-size: 35px;
  font-weight: bold;
  font-family: Arial;
  line-height: 35px;
  transition: transform 0.5s cubic-bezier(0.68, -0.55, 0.27, 1.55); /* 弹性效果 */
}

.plus-sign.rotate {
  transform: rotate(360deg); /* 旋转 360 度 */
}

.modules-container {
  padding-top: 5px; 
  padding-bottom: 80px;
  width: 100%;  /* 容器宽度占满 */
  display: flex;
  flex-direction: column; /* 将模块垂直排列 */
  align-items: center;  /* 水平居中对齐 */
  gap: 10px;  /* 设置模块之间的间距 */
  padding-left: 10px;  /* 左右间距 */
  padding-right: 10px;
}
.group-container {
  width: 100%;
  padding: 0px;
  box-sizing: border-box;
}
.clickable-module {
  background-color: transparent; /* 背景透明 */
  color: #333; /* 字体颜色 */
  padding: 0px 11px;
  border: none;
  font-size: 16px;
  cursor: pointer;
  user-select: none;
  width: 100%;  /* 宽度占满父容器 */
  max-width: 400px;  /* 限制最大宽度*/
  margin-left: auto;  /* 左右居中 */
  margin-right: auto;
  text-align: center;
  z-index: 1;
  box-sizing: border-box;
  border-radius: 25px;
}

.clickable-module:hover {
  background-color: transparent; /* 悬浮时的背景色 */
}

.loading-more {
  margin: 20px;
  font-size: 14px;
  color: #999;
}

/* 分隔线样式 */
.date-divider {
  width: 100%;
  text-align: center;
  margin: 10px 0;
}

.date-text {
  display: inline-block;
  padding: 5px 15px;
  background-color: #f0f0f0;
  font-size: 14px;
  color: #888;
  border-radius: 12px;
  font-weight: bold;
}

/* 卡片和分隔线之间的间距 */
.module-group {
  margin-bottom: 10px;
}

.filter-container {
  width: 100%;
  padding: 10px;
  background-color: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.filter-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.filter-item text {
  font-size: 16px;
  color: #333;
}

.picker {
  padding: 5px 10px;
  background-color: white;
  border-radius: 5px;
  border: 1px solid #ddd;
}

.picker text {
  color: #666;
}


</style>